package cn.rubintry.bug.lib.umeng

import android.content.Context
import android.util.Log
import anet.channel.strategy.dispatch.DispatchConstants.CHANNEL
import anet.channel.util.Utils.context
import com.orhanobut.hawk.Hawk
import com.umeng.commonsdk.UMConfigure
import com.umeng.message.PushAgent
import com.umeng.message.api.UPushRegisterCallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


object UmengInitializer {

    val TAG= UmengInitializer::class.java.canonicalName

    private val AGREE_FLAG = "UmengInitializer:userAgree"

    @JvmStatic
    fun preInit(context: Context){
        UMConfigure.preInit(context, BuildConfig.UMENG_APP_KEY, PushConstants.CHANNEL)
    }

    /**
     * @param context 一定要加这个参数，否则容易导致context不同而集成失败
     */
    @JvmStatic
    fun initialize(context: Context){
        //初始化逻辑
        CoroutineScope(Dispatchers.IO).launch {
            UMConfigure.init(
                context,
                BuildConfig.UMENG_APP_KEY,
                PushConstants.CHANNEL,
                UMConfigure.DEVICE_TYPE_PHONE,
                BuildConfig.UMENG_MESSAGE_SECRET
            )
            // 注册推送
            val api = PushAgent.getInstance(context)
            PushHelper.setting(api)
            api.register(object : UPushRegisterCallback {
                override fun onSuccess(deviceToken: String) {
                    Log.i(TAG, "deviceToken: $deviceToken")
                    //注册厂商通道，因为这里用的主体是“个人”，因此无法注册厂商通道（要备案...必须是企业主体或者更高级别）
                    PushHelper.registerDevicePush(context)
                }

                override fun onFailure(errCode: String, errDesc: String) {
                    Log.e(TAG, "register failed! code:$errCode,desc:$errDesc")
                }
            })
        }
    }


    @JvmStatic
    fun isAgree(): Boolean {
        return Hawk.get(AGREE_FLAG) as? Boolean ?: false
    }

    @JvmStatic
    fun setAgree(agree: Boolean){
        Hawk.put(AGREE_FLAG , agree)
    }
}